package otro.ejemplo.blue.tooth2;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.UUID;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class Principal extends Activity {
 
 private static final int REQUEST_ENABLE_BT = 1;
 private static final int REQUEST_Turn_On_Discoverable = 3;
 
 private ListView listDevicesFound;
 private Button btnScanDevice;
 private TextView stateBluetooth;
 private BluetoothAdapter bluetoothAdapter;
 private BluetoothSocket bluetoothSocket;
 private Spinner spnDiscoverableDuration;
 private Button btnTurnOnDiscoverable;
 private Button btnEnviaMsg;
 private EditText etMensaje;
 private OutputStream outStream = null;
 private int posicion  = 0;
 
 private UUID uuid = UUID.fromString("a60f35f0-b93a-11de-8a39-08002009c666");
 
 private BluetoothDevice bluetoothDevice;
 
 private ArrayAdapter<String> btArrayAdapter;
 private ArrayList<String> btList = new ArrayList<String>();
 private String[] optDiscoverableDur = {"10 seg", "60 seg", "120 seg", "240 seg", "300 seg"};
 private int[] valueDiscoverableDur = {10, 60, 120, 240, 300};
 
 /** Called when the activity is first created. */
 //http://android-er.blogspot.mx/2011/05/scan-bluetooth-devices.html
 //https://github.com/simonguest/btphototransfer-sample/blob/master/src/com/simonguest/BTPhotoTransfer/MainActivity.java
 //http://evilzone.org/java/(android)-three-ways-to-send-data-over-bluetooth/
 //http://www.codeproject.com/Questions/316506/Bluetooth-file-transfer-in-android
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.principal);
        
        btnScanDevice = (Button)findViewById(R.id.scandevice);
        
        stateBluetooth = (TextView)findViewById(R.id.bluetoothstate);
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        
        listDevicesFound = (ListView)findViewById(R.id.devicesfound);
        btArrayAdapter = new ArrayAdapter<String>(Principal.this, android.R.layout.simple_list_item_1);
        listDevicesFound.setAdapter(btArrayAdapter);
        listDevicesFound.setOnItemClickListener(listDevicesFoundClick);
        
        spnDiscoverableDuration = (Spinner)findViewById(R.id.discoverableduration);
        btnTurnOnDiscoverable = (Button)findViewById(R.id.turnondiscoverable);
        
        CheckBlueToothState();
        
        btnScanDevice.setOnClickListener(btnScanDeviceOnClickListener);
        btnTurnOnDiscoverable.setOnClickListener(btnTurnOnDiscoverableOnClickListener);
        
        ArrayAdapter<String> adapterDiscoverableDur = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, optDiscoverableDur);
        adapterDiscoverableDur.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spnDiscoverableDuration.setAdapter(adapterDiscoverableDur);
        
        btnEnviaMsg = (Button)findViewById(R.id.btnEnviaMsg);
        btnEnviaMsg.setOnClickListener(btnEnviaPres);
        
        etMensaje = (EditText)findViewById(R.id.etMensaje);


    }
    
    private OnClickListener btnEnviaPres = new OnClickListener() {
		public void onClick(View v) {
			
			sendMessage(bluetoothSocket,etMensaje.getText().toString());
			}
	};
	

	
	  private void sendMessage(BluetoothSocket socket, String msg) {
		    

		  final UUID SPP_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
		    try {
		    	//BluetoothDevice device = bluetoothDevice;
				//bluetoothSocket bluetoothDevice.createRfcommSocketToServiceRecord(SPP_UUID);
				
			    bluetoothAdapter.cancelDiscovery();
			    Log.i("Serv", btList.get(posicion));
			      //btSocket.connect();

		      outStream = bluetoothSocket.getOutputStream();
		      String message = etMensaje.getText().toString();
		      byte[] msgBuffer = message.getBytes();
		      outStream.write(msgBuffer);
		      bluetoothSocket.close();
		      /*
		      
		      byte[] byteString = (msg + " ").getBytes();
		      byteString[byteString.length - 1] = 0;
		      outStream.write(byteString);
		      */
		    } catch (IOException e) {
		      Log.d("BLUETOOTH_COMMS", e.getMessage());
		    }    
		  }
    
    private OnItemClickListener listDevicesFoundClick = new OnItemClickListener() {

		public void onItemClick(AdapterView<?> arg0, View arg1, int pos,	long arg3) {
			Toast.makeText(Principal.this, btArrayAdapter.getItem(pos), Toast.LENGTH_LONG).show();
			bluetoothDevice = bluetoothAdapter.getRemoteDevice(btList.get(pos));
			posicion = pos;
			Log.i("Obteniendo",btList.get(pos));
			pairDevice(bluetoothDevice);
			
		}
	};
    
	
	private void pairDevice(BluetoothDevice device) {
		  try {
		     Log.d("Pairing", "Start Pairing...");
		     String pw="1234";
             bluetoothAdapter.cancelDiscovery();
		    // Method method = device.getClass().getMethod("createRfcommSocket", new Class[]{int.class});  
             //bluetoothSocket = (BluetoothSocket) method.invoke(device, 1);  
             bluetoothSocket = device.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));  
             /*
             Method removeBondMethod = bluetoothDevice.getClass().getDeclaredMethod("setPin",  
                     new Class[] { byte[].class });  
             Boolean returnValue = (Boolean) removeBondMethod.invoke(bluetoothDevice,  
             new Object[] { pw.getBytes()});
             Log.i("returnValue", "" + returnValue);
             */                
             //Method createBondMethod = bluetoothDevice.getClass().getMethod("createBond");  
             //boolean returnValue = (Boolean) createBondMethod.invoke(bluetoothDevice);  
             
             //Log.i("returnValue", "" + returnValue);   
//           socket = device.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));  
             bluetoothSocket.connect();  
		     
		     /*
		      * 		     bluetoothSocket = device.createRfcommSocketToServiceRecord(uuid);
		     bluetoothSocket.connect();
		      */

		  } catch (Exception e) {
		     Log.e("Pairing", e.getMessage());
		  }
		}
	

		protected void onStop() {
			// TODO Auto-generated method stub
			super.onStop();
			unregisterReceiver(ActionFoundReceiver);
		}

 protected void onDestroy() {
  // TODO Auto-generated method stub
  super.onDestroy();
  //unregisterReceiver(ActionFoundReceiver);
 }

 private void CheckBlueToothState(){
     if (bluetoothAdapter == null){
         stateBluetooth.setText("Bluetooth NOT support");
        }else{
         if (bluetoothAdapter.isEnabled()){
          if(bluetoothAdapter.isDiscovering()){
           stateBluetooth.setText("Bluetooth is currently in device discovery process.");
          }else{
           stateBluetooth.setText("Bluetooth is Enabled.");
           btnScanDevice.setEnabled(true);
           btnTurnOnDiscoverable.setEnabled(true);
          }
         }else{
          stateBluetooth.setText("Bluetooth is NOT Enabled!");
          Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
             startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
         }
        }
    }
 
 
	 private Button.OnClickListener btnTurnOnDiscoverableOnClickListener = new Button.OnClickListener(){
		public void onClick(View arg0) {

			registerReceiver(ScanModeChangedReceiver, new IntentFilter(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED));
			Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
			int dur = valueDiscoverableDur[(int)spnDiscoverableDuration.getSelectedItemId()];
			discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, dur);
			startActivityForResult(discoverableIntent, REQUEST_Turn_On_Discoverable);
		}
	};
	    
    private Button.OnClickListener btnScanDeviceOnClickListener = new Button.OnClickListener(){

  public void onClick(View arg0) {
      registerReceiver(ActionFoundReceiver,  new IntentFilter(BluetoothDevice.ACTION_FOUND));
      btList.clear();
   btArrayAdapter.clear();
   bluetoothAdapter.startDiscovery();
  }};

 @Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {

  if(requestCode == REQUEST_ENABLE_BT){
   CheckBlueToothState();
  }
  if (requestCode == REQUEST_Turn_On_Discoverable){
	   if(resultCode == RESULT_OK){

	   }else if (resultCode == RESULT_CANCELED){
	    Toast.makeText(Principal.this, "User Canceled",Toast.LENGTH_LONG).show();
	   }
	  }
 }
    
 private final BroadcastReceiver ActionFoundReceiver = new BroadcastReceiver(){

  @Override
  public void onReceive(Context context, Intent intent) {
   // TODO Auto-generated method stub
   String action = intent.getAction();
   if(BluetoothDevice.ACTION_FOUND.equals(action)) {
             BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
             btArrayAdapter.add(device.getName() + "\n" + device.getAddress());
             btList.add(device.getAddress());
             btArrayAdapter.notifyDataSetChanged();
         }
  }};
  
  private final BroadcastReceiver ScanModeChangedReceiver = new BroadcastReceiver(){

	  public void onReceive(Context context, Intent intent) {

	   String action = intent.getAction();
	   if(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED.equals(action)) {
	    
	    int mode = intent.getIntExtra(BluetoothAdapter.EXTRA_SCAN_MODE, BluetoothAdapter.ERROR);
	    String strMode = "";
	    
	    switch(mode){
	    case BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE:
	     strMode = "mode changed: SCAN_MODE_CONNECTABLE_DISCOVERABLE";
	     break;
	    case BluetoothAdapter.SCAN_MODE_CONNECTABLE:
	     strMode = "mode changed: SCAN_MODE_CONNECTABLE";
	     break;
	    case BluetoothAdapter.SCAN_MODE_NONE:
	     strMode = "mode changed: SCAN_MODE_NONE";
	     break;
	    }
	    
	    Toast.makeText(Principal.this, strMode, Toast.LENGTH_LONG).show();
	         }
	  }};
	  
	  private void setupDevice()  {
		  
		  
	  }
    
}